package com.wenx.v3auth.service;

import com.wenx.v3secure.user.UserDetail;
import com.wenx.v3core.response.R;
import com.wenx.v3openfeign.api.PlatformUserRemoteInfra;
import com.wenx.v3openfeign.dto.PlatformUserAuthInfoDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.wenx.v3core.util.JsonUtils;

import java.util.Collections;
import java.util.LinkedHashMap;

/**
 * 平台用户详情服务
 * 
 * 专门处理平台用户的认证，通过远程调用获取平台用户信息
 * 
 * @author wenx
 */
@Slf4j
@Service("platformUserDetailsService")
@RequiredArgsConstructor
public class PlatformUserDetailsService implements UserDetailsService {

    private final PlatformUserRemoteInfra platformUserRemoteInfra;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String actualIdentifier = username.startsWith("platform:") ?
                username.substring(9) : username;

        R result = platformUserRemoteInfra.getPlatformUserAuthInfoByUsername(actualIdentifier);

        if (result == null || result.getCode() != 0L || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在或已禁用");
        }

        PlatformUserAuthInfoDto authInfo = convertToAuthInfo(result.getData());
        
        return buildUserDetail(authInfo);
    }
    
    /**
     * 转换数据为认证信息对象
     */
    private PlatformUserAuthInfoDto convertToAuthInfo(Object data) {
        if (data instanceof LinkedHashMap) {
            return JsonUtils.objToObj(data, PlatformUserAuthInfoDto.class);
        } else if (data instanceof PlatformUserAuthInfoDto) {
            return (PlatformUserAuthInfoDto) data;
        } else {
            throw new UsernameNotFoundException("用户认证信息格式错误");
        }
    }
    
    /**
     * 构建用户详情对象
     */
    private UserDetail buildUserDetail(PlatformUserAuthInfoDto authInfo) {
        UserDetail userDetail = new UserDetail();
        userDetail.setId(authInfo.getId());
        userDetail.setUsername(authInfo.getUsername());
        userDetail.setPassword(authInfo.getPassword());
        userDetail.setAccountNonExpired(true);
        userDetail.setAccountNonLocked(authInfo.getStatus() == 1);
        userDetail.setCredentialsNonExpired(true);
        userDetail.setEnabled(authInfo.getStatus() == 1);
        userDetail.setAuthoritySet(Collections.emptySet());
        // 设置为平台用户
        userDetail.setPlatformUser(true);
        return userDetail;
    }
}